import {
  View,
  RichText,
  WebView,
  Image,
  Video,
  ChannelVideo,
} from "@tarojs/components";
import { useRouter, useDidShow, setNavigationBarTitle } from "@tarojs/taro";
import { useState, useMemo } from "react";
import { https, $route } from "@utils/index";

const Detail = () => {
  const { params } = useRouter();
  const [courseDetail, setCourseDetail] = useState<Detail>();
  useDidShow(() => {
    getCourseDetail();
  });
  const getCourseDetail = () => {
    https.getCourseDetail(params).then((res) => {
      setCourseDetail(res?.data?.data);
    });
  };
  // 图片教程
  const getImageHtml = (img_urls: string) => {
    return img_urls?.split(",")?.map((url) => (
      <View key={url}>
        <Image src={url} mode="widthFix" className="block w-full h-auto" />
      </View>
    ));
  };
  const getHtml = useMemo(() => {
    const {
      name,
      type,
      content,
      img_url = "",
      link = "",
      video_url = "",
      cover_image = "",
      applet_app_id = "",
      applet_path = "",
    } = courseDetail || {};
    setNavigationBarTitle({
      title: (name as string) || "教程详情",
    });
    // 类型（1=文本，2=图片，3=链接，4=视频，5=小程序，6=视频号）
    if (type == "5") {
      $route({ url: applet_path, appId: applet_app_id });
      return false;
    }
    return {
      "1": (
        <RichText
          className="text-[30px] leading-[60px] text-[#666]"
          nodes={content}
        />
      ),
      "2": getImageHtml(img_url),
      "3": <WebView src={link} />,
      "4": (
        <Video
          src={video_url}
          poster={cover_image}
          autoplay
          direction={90}
          playBtnPosition="center"
          className="w-full h-auto aspect-video"
        />
      ),
      "6": (
        <ChannelVideo
          className="w-full h-full aspect-video"
          objectFit="cover"
          finderUserName={applet_app_id}
          feedId={applet_path}
          autoplay
        ></ChannelVideo>
      ),
    }[type || ""];
  }, [courseDetail]);
  return <View className="p-[30px]">{getHtml}</View>;
};
export default Detail;
